import 'package:demo/empUtils/EMPLayoutUtils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class EMPTextFieldItem extends StatelessWidget {

  final TextEditingController? controller;
  final String title;
  final String hintText;
  final TextInputType keyboardType;
  final FocusNode? focusNode;

  const EMPTextFieldItem({
    super.key,
    this.controller,
    this.title = "", ///输入框标题
    this.hintText = "", ///占位符
    this.keyboardType = TextInputType.text,
    this.focusNode ///输入框的焦点行为
  });

  @override
  Widget build(BuildContext context) {

    final Row buildInsideRow= Row(
      children: <Widget>[
        Text(title),
        EMPLayout.hGap16,
        expandedWidget(),
        EMPLayout.hGap16
      ],
    );

    return Container(
      height: 50,
      margin: const EdgeInsets.only(left: 15),
      width: double.infinity,///宽度占据父容器的全部空间
      decoration: BoxDecoration(///装饰容器的类，可以设置容器的背景、边框、圆角等
        border: Border(///设置边框的类，可以定义容器的边框样式，边框颜色、宽度、边框类型等
          bottom: Divider.createBorderSide(context, width: 0.6),///分割线
        ),
      ),
      // child: buildRow(),///两种写法，写在外部
      child: buildInsideRow,///两种写法，写在内部
    );
  }

  Widget buildRow() {
    return Row(
      children: <Widget>[
        Text(title),
        EMPLayout.hGap16,
        expandedWidget(),
        EMPLayout.hGap16
      ],
    );
  }

  Widget expandedWidget() {
    ///Expanded：自动填充剩余空间的部分
    return Expanded(child: Semantics(///语义组件，描述组件
      label: hintText.isEmpty ? '请输入$title' : hintText,
      child: TextField(
        focusNode: focusNode,
        keyboardType: keyboardType,
        inputFormatters: _getInputFormatters(),
        controller: controller,
        decoration: InputDecoration(///装饰输入框的类，可以设置输入框的外观和行为
          hintText: hintText,
          border: InputBorder.none, ///去掉下划线
          //hintStyle: TextStyles.textGrayC14
        ),
      ),
    ));
  }

  List<TextInputFormatter>? _getInputFormatters() {///输入格式化器列表
    if (keyboardType == const TextInputType.numberWithOptions(decimal: true)) {
      return <TextInputFormatter>[UsNumberTextInputFormatter()];
    }
    if (keyboardType == TextInputType.number || keyboardType == TextInputType.phone) {
      return <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly];
    }
    aa();
    return null;
  }

  void aa() {
    // TODO: implement aa
  }

}

/// 数字、小数格式化（默认两位小数）
class UsNumberTextInputFormatter extends TextInputFormatter {

  UsNumberTextInputFormatter({
    this.digit = 2,
    this.max = 1000000
  });

  /// 允许输入的小数位数，-1代表不限制位数
  final int digit;

  /// 允许输入的最大值
  final double max;

  static const double _kDefaultDouble = 0.001;

  double _strToFloat(String str, [double defaultValue = _kDefaultDouble]) {
    try {
      return double.parse(str);
    } catch (e) {
      return defaultValue;
    }
  }

  ///获取目前的小数位数
  int _getValueDigit(String value) {
    if (value.contains('.')) {
      return value.split('.')[1].length;
    } else {
      return -1;
    }
  }

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    if (value == '.') {
      value = '0.';
      selectionIndex++;
    } else if (value != '' && value != _kDefaultDouble.toString() &&
        _strToFloat(value) == _kDefaultDouble ||
        _getValueDigit(value) > digit || _strToFloat(value) > max) {
      value = oldValue.text;
      selectionIndex = oldValue.selection.end;
    }
    return TextEditingValue(
      text: value,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
